(function() {
	/**
	 * @class YearSeasonPicker
	 * @extends dorado.widget.Control
	 */
	dorado.widget.YearSeasonPicker = $extend(dorado.widget.Control, /** @scope dorado.widget.YearSeasonPicker.prototype */ {
        $className: "dorado.widget.YearSeasonPicker",
        _inherentClassName: "i-year-month-picker",
		_opened: false,
		focusable: true,
		ATTRIBUTES: /** @scope dorado.widget.YearSeasonPicker.prototype */ {
			className: {
				defaultValue: "d-year-month-picker"
			},
			
			/**
			 * 选择的年份
			 * @attribute
			 * @default (new Date).getFullYear()
			 * @type int
			 */
			year: {
				defaultValue: (new Date).getFullYear()
			},

			/**
			 * 选择季度
			 * @attribute
			 * @default 0
			 * @type int
			 */
			season: {
				defaultValue: 1
			},
			yearstart:{},
			yearend:{}
		},

		EVENTS: /** @scope dorado.widget.YearSeasonPicker.prototype */ {
			/**
			 * 当点击确定按钮之后触发的事件
			 * @param {Object} self 事件的发起者，即组件本身。
			 * @param {Object} arg 事件参数。
			 * @return {boolean} 是否要继续后续事件的触发操作，不提供返回值时系统将按照返回值为true进行处理。
			 * @event
			 */
			onPick: {},
			/**
			 * 当点击取消按钮之后触发的事件
			 * @param {Object} self 事件的发起者，即组件本身。
			 * @param {Object} arg 事件参数。
			 * @return {boolean} 是否要继续后续事件的触发操作，不提供返回值时系统将按照返回值为true进行处理。
			 * @event
			 */
			onCancel: {}
		},

		/**
		 * 刷新年份。
		 * @param {int} year 新的年份
		 * @private
		 */
		refreshYear: function(year) {
			var picker = this,yearstart=picker._yearstart,yearend=picker._yearend, oldYear = picker._year, startYear, doms = picker._doms, yearTable = doms.yearTable, remainder;
			
			if(yearstart && yearend){
				
				if(yearend - yearstart <=10 && yearend - yearstart >0){
					year = yearstart,startYear=year;
					for (var i = 0; i < 5; i++) {
						for (var j = 0; j < 2; j++) {
							var cell = yearTable.rows[i].cells[j];
							var realYear =yearstart + i * 2 + j;
							if(realYear <= yearend){
								cell.innerText = realYear;
							}else{
								cell.innerText ="";
							}
						}
					}
				}else if(yearend -yearstart >10){
					year = year ? year : oldYear;
					remainder = year % 10;
					startYear = year - (remainder == 0 ? 10 : remainder) + 1;
					
					for (var i = 0; i < 5; i++) {
						for (var j = 0; j < 2; j++) {
							var cell = yearTable.rows[i].cells[j];
							var realYear =startYear + i * 2 + j;
							if(realYear <= yearend && realYear>=yearstart){
								cell.innerText = realYear;
							}else{
								cell.innerText ="";
							}
						}
					}
				}
			}else{
				year = year ? year : oldYear;
				remainder = year % 10;
				startYear = year - (remainder == 0 ? 10 : remainder) + 1;
				
				for (var i = 0; i < 5; i++) {
					for (var j = 0; j < 2; j++) {
						var cell = yearTable.rows[i].cells[j];
						cell.innerText = startYear + i * 2 + j;
					}
				}
			}
			var lastSelectedCell = picker._lastSelectedYearCell, index = year - startYear, newSelectedCell = yearTable.rows[Math.floor(index / 2)].cells[index % 2];
			
			if (lastSelectedCell) {
				$fly(lastSelectedCell).removeClass("selected");
			}
			
			if (newSelectedCell) {
				$fly(newSelectedCell).addClass("selected");
			}
			
			picker._lastSelectedYearCell = newSelectedCell;
		},

		/**
		 * 刷新月份。
		 * @param {int} month 设置的月份。
		 * @private
		 */
		refreshMonth: function(season) {
			var picker = this, oldSeason = picker._season, doms = picker._doms, seasonTable = doms.seasonTable;
			
			if (isNaN(season)) {
				season = oldSeason ? oldSeason : 0;
			}
			
			var lastSelectedCell = picker._lastSelectedMonthCell, cell = seasonTable.rows[Math.floor(season-1 )].cells[0];
			
			if (lastSelectedCell) {
				$fly(lastSelectedCell).removeClass("selected");
			}
			
			if (cell) {
				$fly(cell).addClass("selected");
			}
			
			picker._lastSelectedMonthCell = cell;
		},

		/**
		 * 更新日期。
		 * @param date
		 * @param month
		 */
		updateDate: function(date, season) {
			var picker = this, year = date;
			
			if (date instanceof Date) {
				picker.set("year", date.getFullYear());
				
			} else {
				if (!isNaN(year) && !isNaN(season)) {
					picker.set("year", year);
					picker.set("season", season);
				}
			}
		},

		refreshDom: function() {
			var picker = this;
			picker.refreshYear(picker._year);
			picker.refreshMonth(picker._season);
			$invokeSuper.call(this, arguments);
		},

		createDom: function() {
			var seasonLabel = $resource("ndp_base_season"), season_label =seasonLabel.split(",");
			var picker = this, doms = {}, dom = $DomUtils.xCreate({
				tagName: "div",
				content: [{
					tagName: "table",
					className: "year-table",
					contextKey: "yearTable",
					content: [
						{ tagName: "tr", className: "number-row", content: [{ tagName: "td" }, { tagName: "td" }] },
						{ tagName: "tr", className: "number-row", content: [{ tagName: "td" }, { tagName: "td" }] },
						{ tagName: "tr", className: "number-row", content: [{ tagName: "td" }, { tagName: "td" }] },
						{ tagName: "tr", className: "number-row", content: [{ tagName: "td" }, { tagName: "td" }] },
						{ tagName: "tr", className: "number-row", content: [{ tagName: "td" }, { tagName: "td" }] },
						{ tagName: "tr", className: "btn-row", content: [
							{ tagName: "td", align: "center", contextKey: "preaYearCell" },
							{ tagName: "td", align: "center", contextKey: "nextYearCell" }
						]}
					]
				}, {
					tagName: "table",
					className: "month-table",
					contextKey: "seasonTable",
					content: [{
						tagName: "tr",
						className: "number-row",
						content: [
							{ tagName: "td", content: season_label[0] } 
						]
					},{
						tagName: "tr",
						className: "number-row",
						content: [
							 
							{ tagName: "td", content: season_label[1] }
						]
					},{
						tagName: "tr",
						className: "number-row",
						content: [
							 
							{ tagName: "td", content: season_label[2] }
						]
					},{
						tagName: "tr",
						className: "number-row",
						content: [
							 
							{ tagName: "td", content: season_label[3] }
						]
					}]
				}]
			}, null, doms);
			
			var monthLastOverCell, yearLastOverCell;
			
			picker._doms = doms;
			
			if (dorado.Browser.msie && dorado.Browser.version == 6) {
				$fly(doms.halfTable).mousemove(function(event) {
					var position = $DomUtils.getCellPosition(event);
					
					if (position && position.element && (position.element != monthLastOverCell || !monthLastOverCell)) {
						if (monthLastOverCell) {
							$fly(monthLastOverCell).removeClass("hover");
						}
						$fly(position.element).addClass("hover");
						monthLastOverCell = position.element;
					}
				}).mouseout(function() {
					if (monthLastOverCell) {
						$fly(monthLastOverCell).removeClass("hover");
					}
					monthLastOverCell = null;
				});
			}
			
			$fly(doms.seasonTable).click(function(event) {
				var position = $DomUtils.getCellPosition(event);
				 
				if (position && position.element) {
					picker.set("season", position.row  + 1);
					picker.fireEvent("onPick", picker);
				}
			});
			
			if (dorado.Browser.msie && dorado.Browser.version == 6) {
				$fly(doms.yearTable).mousemove(function(event) {
					var position = $DomUtils.getCellPosition(event);
					
					if (position && position.element && (position.element != yearLastOverCell || !yearLastOverCell)) {
						if (position.row == 5) {
							return;
						}
						if (yearLastOverCell) {
							$fly(yearLastOverCell).removeClass("hover");
						}
						$fly(position.element).addClass("hover");
						yearLastOverCell = position.element;
					}
				}).mouseout(function() {
					if (yearLastOverCell) {
						$fly(yearLastOverCell).removeClass("hover");
					}
					yearLastOverCell = null;
				});
			}
			
			$fly(doms.yearTable).click(function(event) {
				var position = $DomUtils.getCellPosition(event);
				if (position && position.element) {
					if (position.row == 5) {
						return;
					}
					if("" !=position.element.innerHTML){
						picker.set("year", parseInt(position.element.innerHTML, 10));
					}
				}
			});
			
			var preYearButton = new dorado.widget.SimpleIconButton({
				iconClass: "prev-year-button",
				listener: {
					onClick: function() {
						picker.set("year", picker._year - 10);
					}
				}
			});
			
			var nextYearButton = new dorado.widget.SimpleIconButton({
				iconClass: "next-year-button",
				listener: {
					onClick: function() {
						picker.set("year", picker._year + 10);
					}
				}
			});
			
			preYearButton.render(doms.preaYearCell);
			nextYearButton.render(doms.nextYearCell);
			
			picker.registerInnerControl(preYearButton);
			picker.registerInnerControl(nextYearButton);
			
			
			
			picker.refreshYear();
			picker.refreshMonth();
			
			return dom;
		},
		doOnKeyDown: function(event) {
			var picker = this, year = picker._year, season = picker._season;
			switch (event.keyCode) {
				
				case 38://up arrow
					if (event.ctrlKey) {
						picker.set("year", year - 1);
					}
					break;
				
				case 40://down arrow
					if (event.ctrlKey) {
						picker.set("year", year + 1);
					}
					break;
				case 33://page up
					picker.set("year", year - 10);
					break;
				case 34://page down
					picker.set("year", year + 10);
					break;
				case 13://enter
					picker.fireEvent("onPick", picker);
					return false;
				case 27://esc
					break;
			}
		}
	});
	
	/**
	 * @component Trigger
	 * @class YearSeasonDropDown
	 * @extends dorado.widget.DropDown
	 */
	dorado.widget.YearSeasonDropDown = $extend(dorado.widget.DropDown, /** @scope dorado.widget.YearSeasonDropDown.prototype */{
        $className: "dorado.widget.YearSeasonDropDown",
		ATTRIBUTES: {
			width: {
				defaultValue: 260
			},
			iconClass: {
				defaultValue: "d-trigger-icon-date"
			},
			returnType:{
				defaultValue:"entity"
			},
			preEditor:{
				
			},
			yearstart:{},
			yearend:{}
		},

		createDropDownBox: function(editor) {
			var yearstart = this._yearstart,yearend = this._yearend;
			var seasonLabel = $resource("ndp_base_season"), season_label =seasonLabel.split(",");
			var dropDown = this,view = this.get('view'),preEditor = this.get('preEditor'), returnType=this.get('returnType'), box = $invokeSuper.call(this, arguments), picker = new dorado.widget.YearSeasonPicker({
				listener: {
					onPick: function(picker) {
						var val = view.get('#'+preEditor+'.value'),d;
						var retval ={};
						var code="01";
						var start,end;
						switch(picker._season){
						   case 1:
							   code="01";
							   start = Date.today().set({year:picker._year,month:0,day:1,hour:0,minute:0,second:0});
							   end =new Date(picker._year,2);
							   end.set({ hour:23,minute:59,second:59});
							   end.set({day:Date.getDaysInMonth(picker._year,2)});
							   break;
						   case 2:
							   code="02";
							   start =Date.today().set({year:picker._year,month:3,day:1,hour:0,minute:0,second:0});
							   end =new Date(picker._year,5);
							   end.set({ hour:23,minute:59,second:59});
							   end.set({day:Date.getDaysInMonth(picker._year,5)});
							   break;
						   case 3:
							   code="13";
							   start =Date.today().set({year:picker._year,month:6,day:1,hour:0,minute:0,second:0});
							   end =new Date(picker._year,8);
							   end.set({ hour:23,minute:59,second:59});
							   end.set({day:Date.getDaysInMonth(picker._year,8)});
							   break;   
						   case 4:
							   code="14";
							   start =Date.today().set({year:picker._year,month:9,day:1,hour:0,minute:0,second:0});
							   end =new Date(picker._year,11);
							   end.set({ hour:23,minute:59,second:59});
							   end.set({day:Date.getDaysInMonth(picker._year,11)});
							   break;
						}
						retval.code=picker._year+""+code;
						retval.year =picker._year;
						retval.season=picker._season;
						retval.label=picker._year+$resource("ndp_base_year")+season_label[picker._season-1];
						if(!returnType || "entity" == returnType || "obj" == returnType){
							retval.start = start;
							retval.end = end;
							dropDown.close(retval);
						}else if("code" == returnType){
							dropDown.close(retval.code);
						}else if("start" == returnType){
							if(val){
								if(start<=val){
									throw new dorado.Exception($resource("ndp_base_error_end"));
								}else{
									dropDown.close(start);
								}
							}else{
								dropDown.close(start);
							}
						}else if("end" == returnType){
							if(val){
								if(end<=val){
									throw new dorado.Exception($resource("ndp_base_error_end"));
								}else{
									dropDown.close(end);
								}
							}else{
								dropDown.close(end);
							}
							 
						}
						 
					},
					onCancel: function() {
						dropDown.close();
					}
				},
				yearstart:yearstart,
				yearend:yearend
			});
			
			box.set({
				style: {
					overflow: "hidden",
					height: 190
				},
				control: picker
			});
			return box;
		},

		doOnKeyPress: function(event) {
			var picker = this, retValue = true, ymPicker = picker.get("box.control");
			switch (event.keyCode) {
				case 27: // esc
					picker.close();
					retValue = false;
					break;
				case 13: // enter
					ymPicker.fireEvent("onPick", picker);
					retValue = false;
					break;
				default:
					retValue = ymPicker.onKeyDown(event);
			}
			return retValue;
		}
	});
	
	dorado.widget.View.registerDefaultComponent("defaultYearSeasonDropDown", function() {
		return new dorado.widget.YearSeasonDropDown();
	});
})();
